<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Batchorder extends CI_Controller
{

    /**
     * 批量订单列表
     *
     * Maps to the following URL
     *        http://example.com/index.php/welcome
     *    - or -
     *        http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    function __construct()
    {
        parent::__construct();
        $this->load->model('Function_m','fun');
        $this->pageSize =$this->config->item('pagenum');
    }
    public function batchOrderList() {
        $factorys = $this->fun->getdatabaseslist("db_factory");
        $this->tpl->assign("factorys",$factorys);

        //生产工厂
        $produce_factorys = $this->fun->getdatabaseslist("d_factory_produce");
        $this->tpl->assign("produce_factorys",$produce_factorys);

        //拼接搜索条件
        $join = "";
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = "";
        //$where.=" AND a.status !=3 "; //已作废订单
		if($_COOKIE["classid"]==12)
		{
            if($_COOKIE['department']==5){ //工厂财务都可以看到 方便标完成

            }else{
                $where.=" AND a.factory_id =1";
            }

		}
		if($_COOKIE["classid"]==13)
		{
            if($_COOKIE['department']==5){ //工厂财务都可以看到 方便标完成

            }else{
                $where.=" AND a.factory_id =2";
            }

		}
		if($_COOKIE["classid"]==16)
		{
            if($_COOKIE['department']==5){ //工厂财务都可以看到 方便标完成

            }else{
                $where.=" AND a.factory_id =7";
            }
		}
        //商品编号，创建人，序号
        $search_goods = trim($this->input->get('search_goods'));
        if($search_goods){
            $this->tpl->assign("search_goods", $search_goods);
            $goods = trim($this->input->get('goods'));
            if($goods){
                $this->tpl->assign("goods", $goods);
                if($search_goods == 1){
                    $where .= " AND a.order_id = '$goods' ";
                }elseif ($search_goods==2){
                    $where .= " AND a.goods_code = '$goods' ";
                }elseif($search_goods==3){
                    $where .= " AND a.goods_name = '$goods' ";
                }else{}
            }
        }else{
            //默认按照商品编号或者订单号查询
            $goods = trim($this->input->get('goods'));
            if($goods){
                $this->tpl->assign("goods", $goods);
                $where .= " AND (a.goods_code = '$goods' || a.order_id = '$goods') ";
            }
        }
        //状态
        $search_status = $this->input->get('search_status');
        if($search_status){
            $this->tpl->assign("search_status", $search_status);
            $where .= " AND a.status = $search_status ";
        }else{
            $where .= " AND a.status != 3 ";
        }
        //生产工厂
        $producefactorys = $this->input->get('produce_factorys');
        if($producefactorys){
            $where.=" AND a.produce_factory = '{$producefactorys}' ";
            $this->tpl->assign("producefactorys", $producefactorys);
        }

        //工厂
        $factory_id = $this->input->get('search_factorys');
        if($factory_id){
            $this->tpl->assign("search_factorys", $factory_id);
            $where .= " AND a.factory_id = '$factory_id' ";
            $search_caijian = $this->input->get('search_caijian');
                //根据工厂id获取相关裁剪和车工人员
                if($factory_id==1)
                {
                    $wheregongc = array('department'=>13,"classid"=>12);
                    $wherecaijian = array('department'=>10,"classid"=>12);
                }elseif($factory_id==2)
                {
                    $wheregongc = array('department'=>13,"classid"=>13);
                    $wherecaijian = array('department'=>10,"classid"=>13);

                }elseif($factory_id==3)
                {
                    $wheregongc = array('department'=>13);
                    $wherecaijian = array('department'=>10);
                }else{
                }
                $workers = $this->db->get_where('d_user',$wheregongc)->result_array();
                $caijian = $this->db->get_where('d_user',$wherecaijian)->result_array();

           // $workers = $this->db->get_where('d_user')->result_array();
           // $caijian = $this->db->get_where('d_user')->result_array();
                $this->tpl->assign("arr_workers", $workers);
                $this->tpl->assign("arr_caijian", $caijian);
            if($search_caijian){
                $join = " LEFT JOIN db_batchorder_list b ON a.order_id = b.batchorder_id ";
                $where.= " AND b.caijian_id = $search_caijian ";
                $this->tpl->assign("search_caijian", $search_caijian);
            }
            $search_workers = $this->input->get('search_workers');
            if($search_workers){
                if(!$join){
                    $join = " LEFT JOIN db_batchorder_list b ON a.order_id = b.batchorder_id ";
                }
                $where.= " AND b.workers_id = $search_workers ";
                $this->tpl->assign("search_workers", $search_workers);
            }

        }else{
            /**
            $wheregongc = array();
            $wherecaijian = array();
            $workers = $this->db->get_where('d_user',$wheregongc)->result_array();
            $caijian = $this->db->get_where('d_user',$wherecaijian)->result_array();
            $this->tpl->assign("arr_workers", $workers);
            $this->tpl->assign("arr_caijian", $caijian);
             * */
        }
        //创建人
        $creators = $this->db->get_where('d_user')->result_array();
        $this->tpl->assign("arr_creators", $creators);
        $search_creator = $this->input->get('search_creator');
        if($search_creator){
            $this->tpl->assign("search_creator", $search_creator);
            $where .= " AND a.userid = '$search_creator' ";
        }

        //查询日期
        $search_date = $this->input->get('search_date');
        if($search_date){
            $this->tpl->assign("search_date", $search_date);
            //日期
            if($search_date==1){//创建时间
                $starttime = $this->input->get('starttime');
                if($starttime){
                    $this->tpl->assign("starttime", $starttime);
                    $where .= " AND a.createtime >= '$starttime' ";
                }
                $endtime = $this->input->get('endtime');
                if($endtime){
                    $this->tpl->assign("endtime", $endtime);
                    $where .= " AND a.createtime <= '$endtime 23:59:59' ";
                }
            }
            //var_dump($where);exit;
            //日期
            if($search_date==2){//交货时间
                $starttime = $this->input->get('starttime');
                if($starttime){
                    $this->tpl->assign("starttime", $starttime);
                    $where .= " AND a.real_goods_date >= '$starttime' ";
                }
                $endtime = $this->input->get('endtime');
                if($endtime){
                    $this->tpl->assign("endtime", $endtime);
                    $where .= " AND a.real_goods_date <= '$endtime 23:59:59' ";
                }
            }
            //日期
            if($search_date==3){//下单时间
                $starttime = $this->input->get('starttime');
                if($starttime){
                    $this->tpl->assign("starttime", $starttime);
                    $where .= " AND a.produce_date >= '$starttime' ";
                }
                $endtime = $this->input->get('endtime');
                if($endtime){
                    $this->tpl->assign("endtime", $endtime);
                    $where .= " AND a.produce_date <= '$endtime 23:59:59' ";
                }
            }
            //日期 //打款时间
            if($search_date==4){
                $starttime = $this->input->get('starttime');
                if($starttime){
                    $this->tpl->assign("starttime", $starttime);
                    $where .= " AND a.remit_date >= '$starttime' ";
                }
                $endtime = $this->input->get('endtime');
                if($endtime){
                    $this->tpl->assign("endtime", $endtime);
                    $where .= " AND a.remit_date <= '$endtime 23:59:59' ";
                }
            }
            if($search_date==5){
                $starttime = $this->input->get('starttime');
                if($starttime){
                    $this->tpl->assign("starttime", $starttime);
                    $where .= " AND a.factory_goods_day >= '$starttime' ";
                }
                $endtime = $this->input->get('endtime');
                if($endtime){
                    $this->tpl->assign("endtime", $endtime);
                    $where .= " AND a.factory_goods_day <= '$endtime 23:59:59' ";
                }
            }

        }
        $where .= " GROUP BY a.order_id ";
        //$join = " LEFT JOIN db_batchorder_list b ON a.order_id = b.batchorder_id ";
        //$join = "";
        $join.=" LEFT JOIN d_factory_produce c ON a.produce_factory = c.id ";
        $orderby = " order by a.order_id DESC";
        $fields = " a.order_id,a.accepter,a.goods_code,a.goods_name,a.factory_id,a.price,a.status,a.goods_date,a.property, ".
                  " a.userid,a.create_user,a.memo,a.remit_date,a.real_goods_date,a.factory_goods_day,a.createtime,a.print_flag,a.cang,c.name as produce_factory_name ";
        //导出excel
        $outexcel = trim($this->input->get('outexcel'));
        if($outexcel==1){
            require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
            $objExcel = new PHPExcel();
            $sql = "SELECT {$fields} FROM db_batchorder a ".$join." WHERE 1 ".$where.$orderby;
            $result = $this->db->query($sql)->result_array();
            $objExcel->setActiveSheetIndex(0);
            $objExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
            $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(22);
            $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
            $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
            $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
            $objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(26);
            //设置标题
            $objExcel->setActiveSheetIndex(0)->setCellValue('A1','订单编号');
            $objExcel->setActiveSheetIndex(0)->setCellValue('B1','商品编号');
            $objExcel->setActiveSheetIndex(0)->setCellValue('C1','数量');
            $objExcel->setActiveSheetIndex(0)->setCellValue('D1','价格');
            $objExcel->setActiveSheetIndex(0)->setCellValue('E1','合计');

            foreach($result as $k=>$v){
                $sql = "SELECT sum(product_num) as product_totalnum,group_concat(product_type separator '@@') as product_alltype,group_concat(product_num separator '@@') as product_allnum FROM db_batchorder_list WHERE batchorder_id = '{$v['order_id']}' ";
                $result = $this->db->query($sql)->row_array();
                $v['product_totalnum'] = $result['product_totalnum'];
                $arr_alltype = explode("@@",$result['product_alltype']);
                $arr_allnum = explode("@@",$result['product_allnum']);
                foreach($arr_alltype as $kk=>$vv){
                    $arr_alltype[$kk] = $vv." ".$arr_allnum[$kk];
                }
                $v['product_alltype'] = $arr_alltype ;

                $v['remit_totalmoney'] = $result['product_totalnum']*$v['price'];


                $count = $k+2;
                $objExcel->setActiveSheetIndex(0)->setCellValue('A'.$count,$v['order_id']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('B'.$count,$v['goods_code']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,$v['product_totalnum']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('D'.$count,$v['price']);
                $objExcel->setActiveSheetIndex(0)->setCellValue('E'.$count,$v['remit_totalmoney']);
            }
            $excel_name = date("YmdHis");
            header("Content-type:application/vnd.ms-excel;charset=gb2312");
            header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
            $objWriter->save('php://output');
            exit;


        }


        $list = $this->fun->getalllist('db_batchorder a', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields,$join);
        //echo $this->db->last_query();exit;
        // $list = $this->fun->getalllist('db_batchorder', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields="*");
        foreach($list['list'] as $k=>$v){
            $list['list'][$k]['order_id'] = $v['order_id'];
            $list['list'][$k]['goods_code'] = $v['goods_code'];
            $list['list'][$k]['goods_name'] = $v['goods_name'];
            $list['list'][$k]['accepter'] = $v['accepter'];
            $list['list'][$k]['cang'] = $v['cang'];
            $list['list'][$k]['factory_id'] = $v['factory_id'];
            $list['list'][$k]['price'] = $v['price'];
            $list['list'][$k]['status'] = $v['status'];
            $list['list'][$k]['goods_date'] = $v['goods_date'];
            $list['list'][$k]['property'] = $v['property'];
            $list['list'][$k]['userid'] = $v['userid'];
            $list['list'][$k]['print_flag'] = $v['print_flag'];
            $list['list'][$k]['create_user'] = $v['create_user'];
            $list['list'][$k]['memo'] = $v['memo'];
            $list['list'][$k]['remit_date'] = $v['remit_date'];
            $list['list'][$k]['real_goods_date'] = $v['real_goods_date'];
            $list['list'][$k]['factory_goods_day'] = $v['factory_goods_day'];
            $list['list'][$k]['createtime'] = $v['createtime'];
            $list['list'][$k]['produce_factory_name'] = $v['produce_factory_name'];
            $sql = "SELECT sum(product_num) as product_totalnum,group_concat(product_type separator '@@') as product_alltype,group_concat(product_num separator '@@') as product_allnum FROM db_batchorder_list WHERE batchorder_id = '{$v['order_id']}' ";
            $result = $this->db->query($sql)->row_array();
            $list['list'][$k]['product_totalnum'] = $result['product_totalnum'];
            $arr_alltype = explode("@@",$result['product_alltype']);

            $arr_allnum = explode("@@",$result['product_allnum']);
            foreach($arr_alltype as $kk=>$vv){
                $arr_alltype[$kk] = $vv." ".$arr_allnum[$kk];
            }

            $list['list'][$k]['product_alltype'] = $arr_alltype ;

            $list['list'][$k]['remit_totalmoney'] = $result['product_totalnum']*$v['price'];
            //var_dump($list['list'][$k]['product_alltype']);exit;
            //$list['list'][$k]['product_allnum'] =  explode("@@",$result['product_allnum']);
            //背景黄色 红色标记
            $daystamps = time()-strtotime($v['createtime']);
            $days = floor($daystamps/86400);
            $list['list'][$k]['days'] = $days ; //创建时间与当前日期相差天数


            if($v['goods_date']&&time()>strtotime($v['goods_date'])){
                $list['list'][$k]['goods_days'] = 1 ;
            }else{
                $list['list'][$k]['goods_days'] = 0 ;
            }
            //获取是否存在物料信息
            $sql_material = "SELECT a.id,b.id as material_id FROM db_product_develop a LEFT JOIN db_product_develop_material b ON a.id = b.develop_id WHERE a.sku = '{$v['goods_code']}' ";
            $rs_material  = $this->db->query($sql_material)->row_array();
            $list['list'][$k]['develop_id'] = $rs_material['material_id']?$rs_material['id']:0;


        }
        //echo $this->db->last_query();exit;
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("orderlist", $list["list"]);
        $this ->tpl->display("factory/batchorderlist.tpl");
    }
    public function produceFactoryList(){

        $factorys = $this->fun->getdatabaseslist("db_factory");
        $this->tpl->assign("factorys",$factorys);

        //生产工厂
        $produce_factorys = $this->fun->getdatabaseslist("d_factory_produce");
        $this->tpl->assign("produce_factorys",$produce_factorys);

        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = " AND del_flag = 0 ";
        //生产工厂
        $producefactorys = $this->input->get('produce_factorys');
        if($producefactorys){
            $where.=" AND id = '{$producefactorys}' ";
            $this->tpl->assign("producefactorys", $producefactorys);
        }

        //工厂
        $factory_id = $this->input->get('search_factorys');
        if($factory_id){
            $this->tpl->assign("search_factorys", $factory_id);
            $where .= " AND factoryProperty = '$factory_id' ";
        }
        if($_COOKIE["classid"]==12)
        {
                $where.=" AND factoryProperty =1";
        }
        if($_COOKIE["classid"]==13)
        {
                $where.=" AND factoryProperty =2";
        }
		  if($_COOKIE["classid"]==16)
        {
                $where.=" AND factoryProperty =7";
        }

        $orderby = " ORDER BY id DESC ";

        $this->pageSize = 20;
        $list = $this->fun->getalllist('d_factory_produce', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields="*",$join);
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign('factorylist',$list['list']);
        $this->tpl->display("factory/factorylist.tpl");
    }
    public function addProduceFactory(){
        if($this->input->post()){
              $id = trim($this->input->post('factory_id'));
              $data['name'] = trim($this->input->post('factory_name'));
              $data['phone'] = trim($this->input->post('phone'));
              $data['address'] = trim($this->input->post('address'));
              $data['descr'] = trim($this->input->post('memo'));

               $data['factoryProperty'] = $_COOKIE["classid"];
                if($_COOKIE["classid"]==12)
                {
                    $data['factoryProperty'] = 1;
                }
                if($_COOKIE["classid"]==13)
                {
                    $data['factoryProperty'] = 2;
                }
				 if($_COOKIE["classid"]==16)
                {
                    $data['factoryProperty'] = 7;
                }
              $data['userid'] = $_COOKIE['userid'];
              $data['username'] = $_COOKIE['username'];
              $data['createtime'] = date("Y-m-d H:i:s");
              if($id){
                  $this->db->update('d_factory_produce',$data," id = '".$id."'");
              }else{
                  $this->db->insert('d_factory_produce',$data);
              }
             header("location:/batchorder/produceFactoryList");
        }else{
            $id = trim($this->input->get_post('id'));
            if($id){
                $sql = "SELECT * FROM d_factory_produce WHERE id = '{$id}' ";
                $rs = $this->db->query($sql)->row_array();
                $this->tpl->assign('factory',$rs);
            }
            $this->tpl->display("factory/addproducefactory.tpl");
        }


    }
    //显示js提示信息
    public function show_js($message,$url){
        echo "<script LANGUAGE='javascript'>alert('$message');</script>";
        if(!empty($url)){
            echo "<script LANGUAGE='javascript'>location.href = '$url';</script>";
        }

    }
    public function addBatchOrder(){
    if($this->input->post()){
        $ary_data = $this->input->post();
        //商品编号进行检索必须存在
        $ary_data['goods_sku'] = trim($ary_data['goods_sku']);
        $sql = "SELECT goods_id,goods_sku,goods_name FROM db_goods WHERE goods_sku = '{$ary_data['goods_sku']}' ";
        $result = $this->db->query($sql)->row_array();
        $url_add = '/batchorder/addBatchOrder';
        if($result){
        }else{
            $msg="该商品编号不存在，请重新输入";
            $this->show_js($msg,$url_add);exit;
        }
        $arr_data['goods_code'] = $ary_data['goods_sku'];//商品编号
        $arr_data['factory_id'] = $ary_data['factorys'];//工厂id
        $arr_data['price'] = $ary_data['price'];//工价 目前为批量价
        $arr_data['goods_date'] = $ary_data['finish_day'];//交货日期
        $arr_data['property'] = $ary_data['property'];//属性 1为批量 2为关联
        $arr_data['memo'] = $ary_data['memo'];//备注信息
        $arr_data['goods_name'] = $result['goods_name'];//创建时间
        $arr_data['createtime'] = date("Y-m-d H:i:s");//创建时间
        //对订单数表进行相关操作进行操作
        //protypename 为型号 ordernum订单数量 caijian 为裁剪人员 workers为车工人员
        $arr_orders = array();
        if(isset($ary_data['protypename'])){
            foreach($ary_data['protypename'] as $k=>$v){
                $arr_orders[$k]['product_type'] = str_replace("，",",",$ary_data['protypename'][$k]); //过滤中文逗号
                $arr_orders[$k]['product_type'] = trim($arr_orders[$k]['product_type']); //过滤空格
                $arr_orders[$k]['product_num'] =  $ary_data['ordernum'][$k];
                $arr_orders[$k]['goods_id'] =   $ary_data['attID'][$k];
                $arr_orders[$k]['goods_sku'] =   $ary_data['attsku'][$k];
                $arr_orders[$k]['beizhu'] =  $ary_data['beizhu'][$k]; //备注
            }
        }else{
            $msg="无相关订单";
            $this->show_js($msg,$url_add);exit;
        }
        //事务处理 整体提交
        $this->db->trans_begin();
        try{
            $arr_data['create_user'] = $_COOKIE['username'];
            $arr_data['userid'] = $_COOKIE['userid'];
            $this->db->insert('db_batchorder',$arr_data);
            $insert_id = $this->db->insert_id();
            foreach($arr_orders as $kk=>$vv){
                $arr_order['batchorder_id'] = $insert_id;
                $arr_order['product_type'] = $vv['product_type'];
                $arr_order['product_num'] = $vv['product_num'];
                $arr_order['goods_id'] = $vv['goods_id'];
                $arr_order['goods_sku'] = $vv['goods_sku'];
                //这个应该使用工价
                $sql = "SELECT goods_id,goods_sku,wages FROM db_goods WHERE goods_sku = '{$vv['goods_sku']}' ";
                $rs = $this->db->query($sql)->row_array();
                $arr_order['price'] = $rs['wages']; //工价
                //$arr_order['price'] = $ary_data['price'];
                $arr_order['memo'] = $vv['beizhu']; //orderlist备注信息date:5/18
                $arr_order['createtime'] = date("Y-m-d H:i:s");
                $this->db->insert('db_batchorder_list',$arr_order);
            }
            $this->db->trans_commit();
            $msg = "添加成功";
            $url = "/batchorder/batchOrderList";
            $this->show_js($msg,$url);exit;
        }catch (Exception $e){
            $this->db->trans_rollback();
            $msg =  $e->getMessage();
            $this->show_js($msg);exit;
        }


    }else{
        //获取工厂列表
        $factorys = $this->fun->getdatabaseslist("db_factory");
        //$sql = "SELECT * FROM d_factory_produce ";
        //$rs  = $this->db->query($sql)->result_array();
        $this->tpl->assign("factorys",$factorys);
        //$this->tpl->assign("factorys",$factorys );
        $this->tpl->display('factory/batchorderadd.tpl');
    }


}
    //修改订单操作
    public function updBatchOrder(){
        if($this->input->post()){
            $str_data = $this->input->post('param');

            $ary_data = explode("&",$str_data);
            foreach($ary_data as $k=>$v){
                $tmp_arr = explode("=",$v);
                $arr_data[$tmp_arr[0]] =htmlspecialchars(urldecode($tmp_arr[1]));
            }
           if($arr_data["price"]){
               $arr_order['price'] = $arr_data['price'];
               $sql = "SELECT * FROM db_batchorder WHERE order_id = {$arr_data['order_id']} ";
               $rs  = $this->db->query($sql)->row_array();
               if($rs['price']!=$arr_data['price']){
                   $arr_log = array();
                   $arr_log['createtime']= date("Y-m-d H:i:s");
                   $arr_log['goods_code'] = $rs['goods_code'];
                   $arr_log['order_id'] = $arr_data['order_id'];
                   $arr_log['details']  = "修改价格，原价格：".$rs['price'].",修改为:".$arr_data['price'];
                   $arr_log['userid'] = $_COOKIE['userid'];
                   $arr_log['username'] = $_COOKIE['username'];
                   $this->db->insert('db_batchorder_log',$arr_log);

               }
           }
		   if($arr_data["customer_day"])$arr_order['goods_date'] = $arr_data['customer_day'];
            //工厂预期交货日期
            if($arr_data["factory_goods_day"]){
                $arr_order['factory_goods_day'] = $arr_data['factory_goods_day']; //工厂确定日期
                /**
                $waitday = strtotime($arr_order['factory_goods_day']);
                $order_sql = "SELECT a.goods_id,a.product_num,b.cang FROM db_batchorder_list a LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id WHERE a.batchorder_id = {$arr_data['order_id']} ";
                $order_rs  = $this->db->query($order_sql)->result_array();
                foreach($order_rs as $key=>$value){
                    if($value['cang']=="2号仓"){
                        $sql_goods = "SELECT * FROM db_goods_stock WHERE goods_id = {$value['goods_id']} AND storage_id = 2 ";
                        $rs_goods  = $this->db->query($sql_goods)->row_array();
                    }else{
                        $sql_goods = "SELECT * FROM db_goods_stock WHERE goods_id = {$value['goods_id']} AND storage_id = 1 ";
                        $rs_goods  = $this->db->query($sql_goods)->row_array();
                    }
                    if($rs_goods){
                        $upd = "UPDATE db_goods_stock SET waitnum = {$value['product_num']},waitday = $waitday WHERE id = {$rs_goods['id']} ";
                        $this->db->query($upd);
                    }

                }**/
            }

           if($arr_data["producefactorys"]) $arr_order['produce_factory'] = $arr_data['producefactorys'];
            if(isset($arr_data["accepter"])&&$arr_data["accepter"]) $arr_order['accepter'] = $arr_data['accepter'];
            //$arr = array('code'=>0,'msg'=>$arr_order['produce_factory']);
            //echo json_encode($arr);exit;
            $arr_order['memo'] = $arr_data['memo'];
            $this->db->where('order_id',$arr_data['order_id']);
            $this->db->update('db_batchorder',$arr_order);
            if($this->db->affected_rows()){
                $arr = array('code'=>1,'msg'=>"更新成功!");
                echo json_encode($arr);exit;
            }else{
                $arr = array('code'=>1,'msg'=>"更新失败!");
                echo json_encode($arr);exit;
            }

        }else{
            $order_id = $this->input->get('order_id');
            $this->tpl->assign('order_id',$order_id);
            //获取该订单信息
            $batchorder = $this->db->query("SELECT * FROM db_batchorder WHERE order_id = '$order_id' ")->row_array();
            $this->tpl->assign('batchorder',$batchorder);
            //已作废订单 status 3 重定向作废订单界面
            if($batchorder['status']==3){
                $path = "batchorder/ajaxbutton?op=delBatchOrder&order_id={$order_id}&status=3";
                $url = base_url($path);
                //redirect($url);
            }
          //  if($batchorder['status']==5||$batchorder['status']==2||$batchorder['status']==6){

                //根据工厂id获取相关裁剪和车工人员
                if($batchorder['factory_id']==1)
                {
                    $wheregongc = array('department'=>13,"classid"=>12);
                    $wherecaijian = array('department'=>10,"classid"=>12);
                }elseif($batchorder['factory_id']==2)
                {
                    $wheregongc = array('department'=>13,"classid"=>13);
                    $wherecaijian = array('department'=>10,"classid"=>13);
                }elseif($batchorder['factory_id']==3)
                {
                    $wheregongc = array('department'=>13);
                    $wherecaijian = array('department'=>10);
                }else{
                }
                $workers = $this->db->get_where('d_user',$wheregongc)->result_array();
                $caijian = $this->db->get_where('d_user',$wherecaijian)->result_array();
               // $workers = $this->db->get_where('d_user')->result_array();
                //$caijian = $this->db->get_where('d_user')->result_array();
                $this->tpl->assign("arr_workers", $workers);
                $this->tpl->assign("arr_caijian", $caijian);

           // }
            //获取工厂列表
            $factorys = $this->fun->getdatabaseslist("db_factory");
            $this->tpl->assign("factorys",$factorys );
            //获取生产工厂
            $sql = "SELECT * FROM d_factory_produce ";
            $rs  = $this->db->query($sql)->result_array();
            $this->tpl->assign("producefactorys",$rs);
            //$producefactorys = $this->config->item('producefactorys');
            //$this->tpl->assign("producefactorys",explode("|",$producefactorys));
            //var_dump(explode("|",$producefactorys));exit;
            //显示相关数据
            $fields = "a.id,a.batchorder_id,a.product_type,a.product_num,a.caijian_id,a.workers_id,b.goods_code,b.goods_name,d.thumb_url,b.price,a.memo,b.status,a.goods_sku,a.order_status,f.savenum,a.price as batchorder_price,e.id as produceFactoryId ";
            $sql = "SELECT $fields FROM db_batchorder_list a ".
                    "LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id ".
                    "LEFT JOIN db_goods c ON b.goods_code = c.goods_sku ".
                    "LEFT JOIN db_goods_images d ON c.goods_id = d.goods_id ".
                    "LEFT JOIN d_factory_produce e ON e.id = a.produce_factory ".
                    "LEFT JOIN d_savenum f ON f.productid = c.goods_id and f.productsku = b.goods_code and f.producttypename = a.product_type ".
                    " WHERE a.batchorder_id = '{$order_id}' GROUP BY a.id ";
            $result = $this->db->query($sql)->result_array();
            foreach($result as $kk=>$vv){
                $vv["memo"] = str_replace("<br/><br/>","<br/>",$vv["memo"]);
                $result[$kk]['memo'] = explode("<br/>",$vv["memo"]);
            }

            $this->tpl->assign("batchorder_list",$result);
            $res = $this->db->query("SELECT * FROM db_batchorder_log WHERE order_id = '$order_id' ORDER BY id DESC ")->result_array();
            $this->tpl->assign("logs", $res);
            $this->tpl->assign("msg_flag", $msg_flag);

            $this->tpl->display('factory/batchorderupd.tpl');
        }


    }
    //修改订单各产品型号数量
    public function updBatchOrderList(){
        $arr_post = $this->input->post();

        //var_dump($arr_post);exit;
        $date = date("Y-m-d H:i:s");
        //判断是否选中修改的选项
        $data = array();
        if(isset($arr_post['ppid'])){

			 $flag = 0; //判断是否修改的标记，若有任何一处修改，则将flag 置为1
			 $message = "";
            foreach ($arr_post['ppid'] as $k=>$v){
               // if(empty($arr_post['upd_num'][$k])&&empty($arr_post['upd_memo'][$k])){
                //    continue;
               // }
                $id = $arr_post['ppid'][$k]; //orderlist表id号
                $fields = " a.id,a.product_type,a.product_num,b.goods_code,b.goods_name,a.memo,b.order_id,a.order_status,a.produce_factory,a.caijian_id,a.workers_id,b.status ";
                $sql = "SELECT $fields FROM db_batchorder_list a LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id WHERE a.del_flag = 0 AND a.id = $id ";
                $result = $this->db->query($sql)->row_array();
                //状态为6 说明工厂验收完成，就不用更新该项数据
                //if($result['order_status']==6){
                //    continue;
               // }
                //var_dump($result['memo']);exit;
                //$message.= "商品编号：{$result['goods_code']},型号：{$result['product_type']},";
                if((intval($arr_post['upd_num'][$k])===0||intval($arr_post['upd_num'][$k])>0)&&intval($arr_post['upd_num'][$k])!=$result['product_num']){

                    //如果为工厂验货完成，则不能更新商品数量，因为已经入库
                    if($result['order_status']==6 || $result['status']==8 || $result['status']==7){ //status 为 batchorder表 质检处理传递过来的状态可能直接就跳到 8，没有经过 工厂验货
                       //不能更新相关数量
                     }else{
                        $message .= "商品编号：{$result['goods_code']},型号：{$result['product_type']},"."生产数量：由{$result['product_num']}被修改为：{$arr_post['upd_num'][$k]}<br>";
                        $data ="";
                        $data['product_num'] = $arr_post['upd_num'][$k];
                        $this->db->update('db_batchorder_list',$data,"id=".$arr_post['ppid'][$k]);
                        $flag = 1;

                    }

                }
                //生产工厂
                if(!empty($arr_post['produce_factory'][$k])){
                    //生产工厂查询
                    $sql_f = "SELECT * FROM d_factory_produce WHERE id = '{$arr_post['produce_factory'][$k]}' ";
                    $rs_f  = $this->db->query($sql_f)->row_array();
                    if($arr_post['produce_factory'][$k]!=$result['produce_factory']){
                        if($result['produce_factory']){
                            $message.="商品编号：{$result['goods_code']},型号：{$result['product_type']},"." 生产工厂被修改为：{$rs_f['name']}<br>";
                        }else{
                            $message.="商品编号：{$result['goods_code']},型号：{$result['product_type']},"." 生产工厂被修改为：{$rs_f['name']}<br>";
                        }

                        $data ="";
                        $data['produce_factory'] = $arr_post['produce_factory'][$k];

                        $this->db->update('db_batchorder_list',$data,"id=".$id);
                        $flag = 1;
                    }

                }
                if(!empty($arr_post['upd_memo'][$k])){
                    $message.="商品编号：{$result['goods_code']},型号：{$result['product_type']},"." 备注新增内容：{$arr_post['upd_memo'][$k]}<br>";
					$data ="";
                    if($result['memo']){
                        $data['memo'] = "<br/>".$result['memo'].$arr_post['upd_memo'][$k];
                    }else{
                        $data['memo'] = $arr_post['upd_memo'][$k]."<br/>";
                    }

					  $this->db->update('db_batchorder_list',$data,"id=".$id);
                      $flag = 1;
                }
                if(!empty($arr_post['search_workers'][$k])){
                    //车工人员
                    $sql_f = "SELECT * FROM d_user WHERE id = '{$arr_post['search_workers'][$k]}' ";
                    $rs_f  = $this->db->query($sql_f)->row_array();
                    if($arr_post['search_workers'][$k]!=$result['workers_id']){
                        $message.="商品编号：{$result['goods_code']},型号：{$result['product_type']},"."车工人员被修改为：{$rs_f['name']} <br/>";
                        $data ="";
                        $data['workers_id'] = $arr_post['search_workers'][$k];
                        $this->db->update('db_batchorder_list',$data,"id=".$id);
                        $flag = 1;
                    }

                }
                if(!empty($arr_post['search_caijian'][$k])){
                    //车工人员
                    $sql_f = "SELECT * FROM d_user WHERE id = '{$arr_post['search_caijian'][$k]}' ";
                    $rs_f  = $this->db->query($sql_f)->row_array();
                    if($arr_post['search_caijian'][$k]!=$result['caijian_id']){
                        $message.="商品编号：{$result['goods_code']},型号：{$result['product_type']},"."裁剪人员被修改为：{$rs_f['name']} <br/> ";
                        $data ="";

                        $data['caijian_id'] = $arr_post['search_caijian'][$k];
                        $this->db->update('db_batchorder_list',$data,"id=".$id);
                        $flag = 1;
                    }

                }
                if(!empty($arr_post['protypename'][$k])){
                    $arr_post['protypename'][$k] = trim($arr_post['protypename'][$k]);
                    $arr_post['protypename'][$k] = str_replace("，",",",$arr_post['protypename'][$k]);
                    //产品型号
                    $message.="商品编号：{$result['goods_code']},型号被修改为：{$arr_post['protypename'][$k]}<br/> ";
                    $data ="";

                    $data['product_type'] = $arr_post['protypename'][$k];
                    $this->db->update('db_batchorder_list',$data,"id=".$id);
                    $flag = 1;

                }
                //插入日志数据表 $flag 为该条参数是否修改的依据
            }

			 if($flag && $message){
                    $arr_log = array();
                    $arr_log['createtime']= $date;
                    $arr_log['goods_code'] = $result['goods_code'];
                    $arr_log['order_id'] = $result['order_id'];
                    $arr_log['details']  = $message;
                    $arr_log['userid'] = $_COOKIE['userid'];
                    $arr_log['username'] = $_COOKIE['username'];
                    $this->db->insert('db_batchorder_log',$arr_log);
                }

           $url = $_SERVER['HTTP_REFERER'];
          redirect($url);
        }else{
            $msg = "未选中相关修改项!";
            $url = $_SERVER['HTTP_REFERER'];
            //var_dump($_SERVER['HTTP_REFERER']);exit;
            $this->show_js($msg,$url);
        }

    }
    //搜寻相关人员 finish
    public function searchEmployee(){
        //type 1 为裁剪 2 为车工
        $factory_id = trim($this->input->post('factory_id'));
        if($factory_id==1)
        {
            $wheregongc = array('department'=>13,"classid"=>12);
            $wherecaijian = array('department'=>10,"classid"=>12);
        }elseif($factory_id==2)
        {
            $wheregongc = array('department'=>13,"classid"=>13);
            $wherecaijian = array('department'=>10,"classid"=>13);
        }elseif($factory_id==3)
        {
            $wheregongc = array('department'=>13);
            $wherecaijian = array('department'=>10);
        }else{
             $wheregongc = array();
             $wherecaijian = array();
        }
        $workers = $this->db->get_where('d_user',$wheregongc)->result_array();
        $caijian = $this->db->get_where('d_user',$wherecaijian)->result_array();
        $arr_data = array('code'=>1,'workers'=>$workers,'caijian'=>$caijian);
        echo json_encode($arr_data);exit;
    }

    //检测是否存在车工人员与裁剪人员
    public function isExistsWorkders(){
        //获取batchorder_list表中相关id号
        $str_param = trim($this->input->post('param'),",");
        $arr_id = explode(",",$str_param);
        if(!empty($arr_id)){
            foreach($arr_id as $k=>$v){
                $sql = "SELECT * FROM db_batchorder_list WHERE id = $v AND del_flag = 0 ";
                $res = $this->db->query($sql)->row_array();
                if($res['workers_id']&&$res['caijian_id']){
                }else{
                    $arr = array('code'=>1,'msg'=>'请选择相关车工人员和裁剪人员');
                    echo json_encode($arr);exit;
                }
            }
        }else{
            $arr = array('code'=>1,'msg'=>'未知错误!');//默认复选选中状态，且不能更改
            echo json_encode($arr);exit;
        }
    }

	
	function ajaxbutton()
	{
		$op = $this->input->get_post('op');
        //删除db_batchorder_list备注信息
        if($op=="delMemo"){
            $id   = trim($this->input->post("id"));
            $memo = trim($this->input->post("memo"));
            $sql = "SELECT * FROM db_batchorder_list WHERE id = '{$id}' ";
            $rs  = $this->db->query($sql)->row_array();
            if($rs){
                $remark = str_replace($memo,"",$rs['memo']);
                $arr_remark = explode("<br/>",$remark);
                $str_conn = "";
                foreach($arr_remark as $k=>$v){
                    if($v){
                        $str_conn.= $v."<br/>";
                    }
                }
                $this->db->update("db_batchorder_list",array("memo"=>$str_conn),"id = '".$id."'");
                //同时得要删除相关的信息
                $this->db->delete("db_factory_scanorder","order_id = '{$rs['batchorder_id']}' AND specifications = '{$rs['product_type']}' AND memo = '{$memo}' ");

                if($this->db->affected_rows()){

                    $s = "SELECT * FROM db_batchorder WHERE order_id = '{$rs['batchorder_id']}' ";
                    $r = $this->db->query($s)->row_array();
                    $arr_log = array();
                    $arr_log['createtime']= date("Y-m-d H:i:s");
                    $arr_log['goods_code'] = $r['goods_code'];
                    $arr_log['order_id'] = $rs['batchorder_id'];
                    $arr_log['details']  = "商品编号:".$r['goods_code'].",型号：".$rs['product_type'].",删除备注内容：".$memo;
                    $arr_log['userid'] = $_COOKIE['userid'];
                    $arr_log['username'] = $_COOKIE['username'];
                    $this->db->insert('db_batchorder_log',$arr_log);

                    echo 200;exit;
                }else{
                    echo 202;exit;
                }
            }else{
                echo 201;exit;
            }
        }
        //查看物料信息
        if($op=="getMaterialInfo"){
            $develop_id = trim($this->input->get_post("develop_id"));
            $batchorder_id = trim($this->input->get_post("batchorder_id"));
            $sql_batch = "SELECT SUM(product_num) as totalnum FROM db_batchorder_list WHERE batchorder_id = '{$batchorder_id}' ";
            $rs_batch  = $this->db->query($sql_batch)->row_array();
            $sql = "SELECT * FROM db_product_develop_material WHERE develop_id = {$develop_id} ";
            $rs  = $this->db->query($sql)->result_array();
            foreach($rs as $k=>$v){
                $rs[$k]['totalwages'] = ($v['materialnum']*$v['materwages'])*$rs_batch['totalnum'];
                $rs[$k]['producenum'] = $rs_batch['totalnum'];
                $rs[$k]['totalnum'] = $rs_batch['totalnum']*$v['materialnum'];
                $sql_factory_material = "SELECT * FROM db_factory_material WHERE code = '{$v['materialcode']}' ";
                $rs_factory_material = $this->db->query($sql_factory_material)->row_array();
                $rs[$k]['dw'] = $rs_factory_material['dw']?$rs_factory_material['dw']:"";
                $rs[$k]['cangwei'] = $rs_factory_material['cangwei']?$rs_factory_material['cangwei']:"";
                $rs[$k]['num'] = $rs_factory_material['num']?$rs_factory_material['num']:"";

            }
            $this->tpl->assign("materiallist",$rs);
            $this->tpl->display("/factory/materiallist.tpl");
        }
		if($op =="searchProductPrice")
		{
			//根据商品编号搜索商品价格并显示，备注改价格为商品的批量价格bulkprice
			$goods_sku = trim($this->input->post('goods_id'));
			$sql = "SELECT bulkprice,g_supplier,goods_parentID,wages FROM db_goods WHERE goods_sku = '$goods_sku'";
			$result = $this->db->query($sql)->row_array();
			if($result){
			$listsku = $this->fun->getdatabaseslist("db_goods"," AND goods_parent_sku='".$goods_sku."' AND goods_sku !='".$goods_sku."'","goods_sku,goods_id,goods_name,g_goodstypeID");
			foreach($listsku as $key=>$rs)
			{
				if($rs["g_goodstypeID"] ==0)
				{
					$rs["g_goodstypeID"] = 7;  //默认是衣服属性
				}
				$rgoodstype = $this->db->get_one("SELECT GROUP_CONCAT(attr_value ORDER BY attr_id ASC)  AS sta FROM `db_goods_attr` WHERE `goods_id` = '".$rs["goods_id"]."'");
                //echo $this->db->last_query();exit;
				//$listsku[$key]["goodstypelist"] = $rgoodstype["sta"];
                $arr_conn = explode(",",$rgoodstype['sta']);
                if(!empty($arr_conn[1])){
                    if(mb_substr($arr_conn[0],0,1)=="男"||mb_substr($arr_conn[0],0,1)=="女"){
                        $listsku[$key]["goodstypelist"] = $arr_conn[1].",".$arr_conn[2].",".mb_substr($arr_conn[0],0,1);
                    }else{
                        $listsku[$key]["goodstypelist"] = $arr_conn[1].",".$arr_conn[2].",".$arr_conn[0];
                    }

                }else{
                    $listsku[$key]["goodstypelist"] = "";
                }
                /**
                if(!empty($arr_conn[1])){
                    if(mb_substr($arr_conn[0],0,1)=="男"||mb_substr($arr_conn[0],0,1)=="女"){
                        $listsku[$key]["goodstypelist"] = $arr_conn[1].",".$arr_conn[2].",".mb_substr($arr_conn[0],0,1);
                    }else{
                        $listsku[$key]["goodstypelist"] = $arr_conn[1].",".$arr_conn[2].",".$arr_conn[0];
                    }

                }else{
                    $listsku[$key]["goodstypelist"] = "";
                }**/

			}
		
			$arr_data = array('code'=>1,'msg'=>$result['wages'],"g_supplier"=>$result['g_supplier'],"goods_parentID"=>$result['goods_parentID'],"countlistsku"=>count($listsku),"listsku"=>$listsku);
			echo json_encode($arr_data);exit;
			}else{
			$arr_data = array('code'=>0,'msg'=>"该商品编号不存在");
			echo json_encode($arr_data);exit;
			}
		
		}
		
		if($op =='savebatchexcel')
		{
			require_once BASEPATH.'../fuman/ClassesExcel/PHPExcel/IOFactory.php';
			$res = $this->fun->newupfile('upfile','factory');
			//$res['pic']  = "factory/20170724/20170724134742334.xls";
			$upfile =BASEPATH.'../uploads/'.$res['pic'];
			if(!file_exists($upfile))
			{
				echo "没找到文件->". $upfile;
				die;
			}

			if($resExcel = PHPExcel_IOFactory::load($upfile)){
				$allRow = $resExcel->getActiveSheet()->getHighestRow();
				$s = 0;
				for($i=2;$i<=$allRow;++$i){
					$goods_sku=trim($resExcel->getActiveSheet()->getCell('A'.$i)->getValue());	//sku
					$B=trim($resExcel->getActiveSheet()->getCell('B'.$i)->getValue());	//商品型号及数量（型号,版型,性别)
					$C=trim($resExcel->getActiveSheet()->getCell('C'.$i)->getValue());	//所属工厂(工厂1,工厂2)
					$D=trim($resExcel->getActiveSheet()->getCell('D'.$i)->getValue());	//订单属性（批量，关联)
					$F=trim($resExcel->getActiveSheet()->getCell('F'.$i)->getValue());	//仓库
					$finish_day=trim($resExcel->getActiveSheet()->getCell('E'.$i)->getValue());	//期望交货时间
					$G=trim($resExcel->getActiveSheet()->getCell('G'.$i)->getValue());	//备注

					$time = ($finish_day - 25569) * 24*60*60;
					$finish_day =  date('Y-m-d', $time);

					if($C == '工厂1') $factorys = 1; 
					if($C == '工厂2') $factorys = 2; 

					if($D == '关联') $property = 1; 
					if($D == '批量') $property = 2; 
					$goodsinfo = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku = '".$goods_sku."'");
                    //获取相关数值 仅仅获取一条数据即可判断
                    $sql_num = "SELECT * FROM db_goods WHERE goods_parent_sku = '{$goods_sku}' AND goods_sku != '{$goods_sku}' ";
                    //$rs_num  = $this->db->query($sql_num)->row_array();
                    $rs_num  = $this->db->query($sql_num)->result_array();
                    //print_r($rs_num);exit;
                    //$sku_num = explode("-",$rs_num['goods_sku']);
                    //$sku_num = $sku_num[0]; //sku尺码前缀

					$goods_name = $goodsinfo['goods_name'];
					//$price = $goodsinfo['bulkprice'];
                    $price = $goodsinfo['wages']; //使用工价

					$arr_data['goods_code'] = $goods_sku;//商品编号
					$arr_data['factory_id'] = $factorys;//工厂id
					$arr_data['price'] = $price;//工价
					$arr_data['goods_date'] = $finish_day;//交货日期
					$arr_data['property'] = $property;//属性 1为批量 2为关联
					$arr_data['memo'] = $G;//备注信息
					$arr_data['cang'] = $F;//备注信息
					$arr_data['goods_name'] = $goods_name;
					$arr_data['createtime'] = date("Y-m-d H:i:s");//创建时间
					$arr_data['create_user'] = $_COOKIE['username'];
					$arr_data['userid'] = $_COOKIE['userid'];
					 $this->db->trans_begin();
					$this->db->insert('db_batchorder',$arr_data);
					$insert_id = $this->db->insert_id();
					
					$goods =explode("\n",$B);
					foreach($goods as $key=>$vv)
					{
                        $product_type = explode(" ",$vv);
                        $product = $product_type[0];
                        $product_num = $product_type[1];

                        $product = str_replace("，",",",$product);
                        $xm = explode(",",$product);

                        //rs_num为通过商品查出的sku的集合
                        $orgin_product_sku =  explode(",",$product);
                        foreach($rs_num as $kkk=>$vvv){

                            $rgoodstype = $this->db->get_one("SELECT GROUP_CONCAT(attr_value ORDER BY attr_id DESC)  AS sta FROM `db_goods_attr` WHERE `goods_id` = '".$vvv["goods_id"]."'");
                            $arr_conn = explode(",",$rgoodstype['sta']);
                             foreach($orgin_product_sku as $k_sku=>$v_sku){
                                    if($k_sku==2){
                                        if($v_sku=="男"||$v_sku=="女"){
                                            $orgin_product_sku[$k_sku] = $v_sku."性";
                                        }else{
                                            $orgin_product_sku[$k_sku] = $v_sku;
                                        }
                                    }else{
                                        $orgin_product_sku[$k_sku] = $v_sku;
                                    }
                             }

                            if(in_array($arr_conn[1],$orgin_product_sku)&&in_array($arr_conn[2],$orgin_product_sku)&&in_array($arr_conn[0],$orgin_product_sku)){
                                $sku_num = explode("-",$vvv['goods_sku']);
                                $sku_num = $sku_num[0]; //sku尺码前缀
                                break;
                            }
                            //判断是否为性别 欧美等是否为通用
                            if($arr_conn[0]=="通用"){
                                if($arr_conn[2]=="通用"){
                                    if(in_array($arr_conn[1],$orgin_product_sku)){
                                        $sku_num = explode("-",$vvv['goods_sku']);
                                        $sku_num = $sku_num[0]; //sku尺码前缀
                                        break;
                                    }

                                }else{
                                    if(in_array($arr_conn[2],$orgin_product_sku)&&in_array($arr_conn[1],$orgin_product_sku)){
                                        $sku_num = explode("-",$vvv['goods_sku']);
                                        $sku_num = $sku_num[0]; //sku尺码前缀
                                        break;
                                    }


                                }

                            }
                            if($arr_conn[2]=="通用"){
                                if($arr_conn[0]=="通用"){
                                    if(in_array($arr_conn[1],$orgin_product_sku)){
                                        $sku_num = explode("-",$vvv['goods_sku']);
                                        $sku_num = $sku_num[0]; //sku尺码前缀
                                        break;
                                    }

                                }else{
                                    if(in_array($arr_conn[0],$orgin_product_sku)&&in_array($arr_conn[1],$orgin_product_sku)){
                                        $sku_num = explode("-",$vvv['goods_sku']);
                                        $sku_num = $sku_num[0]; //sku尺码前缀
                                        break;
                                    }

                                }

                            }
                            
                            /**
                            $str_sku = $arr_conn[1].",".$arr_conn[2].",".mb_substr($arr_conn[0],0,1);
                            if($str_sku==$product){
                                $sku_num = explode("-",$vvv['goods_sku']);
                                $sku_num = $sku_num[0]; //sku尺码前缀
                                break;
                            }**/
                        }
                        // 9 /4
                        if($sku_num){
                            $vvgoods_sku = $sku_num."-".strtoupper($xm[0]); //$xm[0]为 S L 等尺码
                        }else{
                            $vvgoods_sku = strtoupper($xm[0]);
                        }
						//$vvgoods_sku = $xm[0];
						$goodsinfo = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku = '".$vvgoods_sku."'");
						$vvgoods_id = $goodsinfo['goods_id'];

						//$vvprice = $goodsinfo['bulkprice'];
                        $vvprice = $goodsinfo['wages']; //使用工价
						if(!$vvprice)
						{
							$vvprice = $price;
						}else{
							$this->db->update('db_batchorder',array("price"=>$vvprice),"order_id ='".$insert_id."'");
						}
						$arr_order = "";
						$arr_order['batchorder_id'] = $insert_id;
						$arr_order['product_type'] = $product;
						$arr_order['product_num'] = $product_num;
                        if($vvgoods_id){
                            $arr_order['goods_id'] = $vvgoods_id;
                            $arr_order['price'] = $goodsinfo['wages']; //使用的是工价
                            $arr_order['goods_sku'] = $vvgoods_sku;
                        }
						//$arr_order['price'] = $vvprice;
						$arr_order['memo'] =''; //orderlist备注信息date:5/18
						$arr_order['createtime'] = date("Y-m-d H:i:s");
						$this->db->insert('db_batchorder_list',$arr_order);
					}
					

					

					if ($this->db->trans_status() === FALSE)
					{
						$this->db->trans_rollback();
					}
					else
					{
						$this->db->trans_commit();
					}

				}
			}

			header("location:/batchorder/batchOrderList");

		
		}
        //获取batchorder_list数据
        if($op=='getOneBatchData'){
            $id = $this->input->post('id');
            $sql = "SELECT a.goods_id,b.factory_id,a.id as batch_id,a.goods_sku,a.product_type,a.product_num,a.batchorder_id,b.goods_code,b.goods_name FROM db_batchorder_list a LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id WHERE a.id = '".$id."'";
            $rs  = $this->db->query($sql)->row_array();
            echo json_encode($rs);exit;
        }
        if($op=="updProduceFactory"){
            $id = trim($this->input->post('id'));
            $order_id = trim($this->input->post('order_id'));
            $s_batchorder = "SELECT * FROM db_batchorder WHERE order_id = '{$order_id}' ";
            $r_batchorder = $this->db->query($s_batchorder)->row_array();

            $sql = "SELECT * FROM db_batchorder WHERE produce_factory = '{$id}' AND goods_code = '{$r_batchorder['goods_code']}' ORDER BY order_id DESC  ";
            $rs  = $this->db->query($sql)->row_array();
            if(count($rs)>0){
                $arr = array('code'=>200,"wages"=>$rs['price']);
            }else{
                $sql_batch = "SELECT * FROM db_batchorder a LEFT JOIN db_goods b ON a.goods_code = b.goods_sku WHERE a.order_id = '{$order_id}' ";
                $rs_bath   = $this->db->query($sql_batch)->row_array();

                $arr = array('code'=>200,"wages"=>$rs_bath['wages']);
            }
            echo json_encode($arr);exit;

        }
        if($op=='delProduceFactory'){
            $id = $this->input->get_post('id');
            $sql = "SELECT * FROM d_factory_produce WHERE id = '{$id}' ";
            $rs  = $this->db->query($sql)->row_array();
            if($rs){
                $this->db->update('d_factory_produce',array('del_flag'=>1)," id = '".$id."'");
            }
            header("location:/batchorder/produceFactoryList");
        }
        if($op =='savescanorder')
        {
            //过渡阶段，判断该工厂订单是否从采购列表那边过来的
            $orderId = trim($this->input->post('order_id'));
            $sql_purlist = "SELECT * FROM db_purchase_list WHERE tb_ordersn = '{$orderId}' ";
            $rs_purlist  = $this->db->query($sql_purlist)->row_array();
            if(count($rs_purlist)>0){
                echo "该批量工厂订单无法操作，请在质检处理中，添加相关操作!";exit;
            }
            $goods =  $this->fun->getdatabasesdetail("db_goods"," AND goods_sku='". trim($this->input->post('goods_sku'))."'");
            $postst="";
            $postst["order_id"] = trim($this->input->post('order_id'));
            $postst["goods_sku"] = trim($this->input->post('goods_sku'));
            $postst["goods_sub_sku"] = trim($this->input->post('goods_sub_sku'));
            $postst["goods_id"] = $goods["goods_id"];
            $postst["skuName"] = $goods["goods_name"];
            $postst["goods_num"] = trim($this->input->post('goods_num'));
            $postst["price"] = $goods["bulkprice"];
            $postst["specifications"] =trim($this->input->post('specifications'));

            $fID = trim($this->input->post('fID'));
            if($fID==1)
            {
                $factorylistname = "工厂1";
                $factoryID = 1;
            }
            if($fID==2)
            {
                $factorylistname = "工厂2";
                $factoryID = 2;
            }
            $postst["factoryID"] = $factoryID;
            $postst["factoryName"] = $factorylistname;
            $postst["settlementtime"] = trim($this->input->post('insttime'));
            $postst["insttime"] = date("Y-m-d");
            $postst["oper"] = $_COOKIE["username"];
            $postst["type"] =2;
            $postst['memo'] = trim($this->input->post('remarks'));
            $this->db->insert("db_factory_scanorder",$postst);

            //更新备注信息，以及日志
            $id = $this->input->post('batch_id');
            $remarks = trim($this->input->post('remarks'))."<br/>";

            $sql = "SELECT * FROM db_batchorder_list WHERE id = '".$id."'";
            $result = $this->db->query($sql)->row_array();
            if($result['memo']){
                $memo = "<br/>".$result['memo'].$remarks;
            }else{
                $memo = $remarks."<br/>";
            }

            $this->db->update("db_batchorder_list",array('memo'=>$memo),"id = '".$id."'");
            //echo $this->db->last_query();exit;
            //插入日志记录
            $message ="商品编号：{$postst["goods_sku"]},型号：{$postst["specifications"]},"." 备注新增内容：{$remarks}";
            $arr_log = array();
            $arr_log['createtime']= date("Y-m-d H:i:s");
            $arr_log['goods_code'] = $postst["goods_sku"];
            $arr_log['order_id'] = $postst["order_id"];
            $arr_log['details']  = $message;
            $arr_log['userid'] = $_COOKIE['userid'];
            $arr_log['username'] = $_COOKIE['username'];
            $this->db->insert('db_batchorder_log',$arr_log);


            echo 200;
            die;
        }
		if($op == 'orderPrint')
		{
		    $str_param = trim($this->input->get('param'),",");
            $arr_order_id = explode(",",$str_param); //order_id数组
            $arr_print = array(); //需要打印出来的数据
            $date = date("Y-m-d H:i:s");
            foreach($arr_order_id as $k=>$v){
                    $sql = "";
                    $sql = "SELECT produce_date FROM db_batchorder WHERE order_id = '{$v}' ";
                    $rs  = $this->db->query($sql)->row_array();
                    if(!$rs['produce_date']){
                        $this->db->update("db_batchorder",array('produce_date'=>$date)," order_id = '".$v."'");
                    }
                    //$v 为获取到的选中的id号 订单号
                    $fields = "a.id,g.name as caijian_name,j.name as workers_name,f.name as factory_name,d.thumb_url,d.local_url,c.standard,c.goods_sku,c.goods_name,b.order_id,b.produce_date,b.goods_date,b.create_user,a.product_type,a.product_num,a.memo ";
                    $this->db->from('db_batchorder_list a');
                    $this->db->select($fields);
                    $this->db->where('a.batchorder_id',$v);
                    $this->db->join('db_batchorder b','b.order_id = a.batchorder_id and a.del_flag = 0','left');
                    $this->db->join('db_goods c','b.goods_code = c.goods_sku','left');
                    $this->db->join('db_goods_images d','c.goods_id = d.goods_id','left');
                    $this->db->join('db_factory f','b.factory_id = f.id ','left');
                    $this->db->join('d_user g','a.caijian_id = g.id ','left');
                    $this->db->join('d_user j','a.workers_id = j.id ','left');
                    $this->db->group_by('a.id');
                    $arr_orders = $this->db->get()->result_array();
                    $arr_print[$v] = $arr_orders;
                    //更新订单打印状态
                    $data['print_flag'] = 1;
                    $this->db->where('order_id',$v);
                    $this->db->update('db_batchorder',$data);

            }
            $this->tpl->assign("prints", $arr_print);
            $this->tpl->display('factory/batchorderprints.tpl',0,0,1);
		}
		//修改订单状态 9/15
        if($op == "updOrderStatus"){
            $data['status'] = $this->input->post('status');
            $str_order = trim($this->input->post('order_id'),","); // 格式：27,28,29
            $arr_order = explode(",",$str_order);

            //标生产情况下 有工厂预期交货日期
            $str_dates = $this->input->post('str_dates');
            $arr_dates = explode(",",$str_dates);

            $flag = 0;

            foreach($arr_order as $key=>$value){
                $sql = "SELECT * FROM db_batchorder WHERE order_id = $value ";
                $rs  = $this->db->query($sql)->row_array();
                if($rs){
                    $arr_things['createtime'] = date("Y-m-d H:i:s");
                    $arr_things['order_id'] = $value;
                    $arr_things['goods_code'] = $rs['goods_code'];
                    $arr_things['details'] = "";

                    if($rs['status']==4&&$data['status']==1){
                        if($rs['produce_date']){
                        }else{
                            $data['produce_date'] = date("Y-m-d"); //标生产
                        }
                        $data['factory_goods_day']=$arr_dates[$key]; //工厂预期交货日期
                        $this->db->update('db_batchorder',$data," order_id=".$value);
                        if($this->db->affected_rows()){
                            $arr_things['details'] = "状态：新订单被修改为：开始生产";
                            $flag = 1;
                        }

                    }
                    //生产中或标交货状态可以标作废 新订单
                    if(($rs['status']==1 || $rs['status']==5 || $rs['status']==4)&&$data['status']==3){
                        //$data['produce_date'] = date("Y-m-d"); //标作废
                        $this->db->update('db_batchorder',$data," order_id=".$value);
                        if($this->db->affected_rows()){
                            $arr_things['details'] = "状态：新订单被修改为: 作废";
                            $flag = 1;
                        }
                    }
                    //开始生产状态可以标交货
                    if($rs['status']==1&&$data['status']==5){
                        $data['real_goods_date'] = date("Y-m-d H:i:s");//标交货
                        $this->db->update('db_batchorder',$data," order_id=".$value);
                        if($this->db->affected_rows()){
                            $arr_things['details'] = "状态：开始生产被修改为：确认交货";
                            $flag = 1;
                        }
                    }
                    //公司验收完成状态可以批量标打款 只有工厂人员可以操作
                    if($rs['status']==7&&$data['status']==8){
                        //只有工厂1  工厂2的人可以操作
                        if($_COOKIE['classid']==12 ||$_COOKIE['classid']==13 ||$_COOKIE['classid']==16){
                            $this->db->update('db_batchorder',$data," order_id=".$value);
                            if($this->db->affected_rows()){
                                $arr_things['details'] = "状态：公司验收完成被修改为：已打款";
                                $flag = 1;
                            }
                        }
                    }
                    //打款状态可以标完成  只有工厂人员可以操作
                    if($rs['status']==8&&$data['status']==2){
                        //只有工厂1  工厂2的人可以操作
                        if($_COOKIE['classid']==12 ||$_COOKIE['classid']==13 ||$_COOKIE['classid']==16){
                            $this->db->update('db_batchorder',$data," order_id=".$value);
                            if($this->db->affected_rows()){
                                $arr_things['details'] = "状态：确认打款被修改为：已完成";
                                $flag = 1;
                            }
                        }
                    }
                    if($arr_things['details']){
                        $arr_things['username'] = $_COOKIE['username'];
                        $arr_things['userid'] = $_COOKIE['userid'];
                        $this->db->insert('db_batchorder_log', $arr_things);
                    }

                }

            }
            //返回值
            if($data['status']==1&&$flag == 1){
                $msg = "标生产成功!";
            }
            if($data['status']==5&&$flag == 1){
                $msg = "标交货成功!";
            }
            if($data['status']==3&&$flag == 1){
                $msg = "标作废成功!";
            }
            if($data['status']==2&&$flag == 1){
                $msg = "标完成成功!";
            }
            if($data['status']==8&&$flag == 1){
                $msg = "标打款成功!";
            }
            if($flag==1){
                $arr_ret = array('code'=>200,'msg'=>$msg);
            }else{
                $arr_ret = array('code'=>201,'msg'=>"操作失败");
            }
            echo json_encode($arr_ret);

            exit;

        }

		if($op =="delBatchOrder")
	{
		 //status 1为生产 3为作废
        $data['status'] = $this->input->get('status');
        $order_id = $this->input->get('order_id');
        //工厂预期交货日期 仅仅针对生产中
        $factory_goods_day = $this->input->get('factory_goods_day');
        //获取该订单信息
            $this->db->where('order_id',$order_id);
            if($data['status']==1){ //开始生产
                $sql = "SELECT * FROM db_batchorder WHERE order_id = '{$order_id}' ";
                $rs  = $this->db->query($sql)->row_array();
                if($rs['produce_date']){
                }else{
                    $data['produce_date'] = date("Y-m-d");
                }
                $data['factory_goods_day'] = $factory_goods_day;

                /**
                $waitday = strtotime($factory_goods_day);
                $order_sql = "SELECT a.goods_id,a.product_num,b.cang FROM db_batchorder_list a LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id WHERE a.batchorder_id = {$order_id} ";
                $order_rs  = $this->db->query($order_sql)->result_array();
                foreach($order_rs as $key=>$value){
                    if($value['cang']=="2号仓"){
                        $sql_goods = "SELECT * FROM db_goods_stock WHERE goods_id = {$value['goods_id']} AND storage_id = 2 ";
                        $rs_goods  = $this->db->query($sql_goods)->row_array();
                    }else{
                        $sql_goods = "SELECT * FROM db_goods_stock WHERE goods_id = {$value['goods_id']} AND storage_id = 1 ";
                        $rs_goods  = $this->db->query($sql_goods)->row_array();
                    }
                    if($rs_goods){
                        $upd = "UPDATE db_goods_stock SET waitnum = {$value['product_num']},waitday = $waitday WHERE id = {$rs_goods['id']} ";
                        $this->db->query($upd);
                    }

                }**/

            }elseif ($data['status']==5){ //确认交货
                $data['real_goods_date'] = date("Y-m-d H:i:s");
            }elseif ($data['status']==8){ //打款日期
                $data['remit_date'] = date("Y-m-d");
            }elseif ($data['status']==2){ //已完成的相关操作
                $search_workers = $this->input->get('search_workers');
                $search_caijian = $this->input->get('search_caijian');
                //需要对orderlist车工和裁剪工人进行更新操作
            }elseif ($data['status']==6){ //工厂验货完成 要进行判断
                $accepter = $this->input->get('accepter');
                $produce_factory = $this->input->get('produce_factory');
                $data['accepter'] = $accepter;
                $data['produce_factory']=$produce_factory;
            }else{}
            $this->db->update('db_batchorder',$data);
            $batchorder = $this->db->query("SELECT * FROM db_batchorder WHERE order_id = '$order_id' ")->row_array();
            $this->tpl->assign('batchorder', $batchorder);
            if($this->db->affected_rows()) {
                //操作事项
                $arr_things['createtime'] = date("Y-m-d H:i:s");
                $arr_things['order_id'] = $order_id;
                $arr_things['goods_code'] = $batchorder['goods_code'];
                if($data['status']==3){
                    $arr_things['details'] = "状态：新订单被修改为: 作废";
                }elseif($data['status']==1){
                    $arr_things['details'] = "状态：新订单被修改为：开始生产";
                }elseif($data['status']==5){
                    $arr_things['details'] = "状态：开始生产被修改为：确认交货";
                }elseif($data['status']==6){ //9/5 该功能是对整个工厂验收完成 暂停使用，目前点击每个完成工厂验收
                    $arr_things['details'] = "状态：确认交货被修改为：工厂验货完成";
                    $date = date("Y-m-d H:i:s");
                    //整体操作开始 start
                     $str_id = trim($this->input->get('param'),","); //batchorder_list 的id数组
                     $arr_id = explode(",",$str_id);
                     $str_caij = trim($this->input->get('caij'),",");
                     $arr_caij = explode(",",$str_caij);
                     $str_work = trim($this->input->get('work'),",");
                     $arr_work = explode(",",$str_work);
                     $str_num = trim($this->input->get('num'),",");
                     $arr_num = explode(",",$str_num);
                        if(!empty($arr_id)){
                            foreach ($arr_id as $k=>$v){
                                $id = $v; //orderlist表id号
                                $fields = "a.id,a.product_type,a.product_num,a.goods_id,b.goods_code,b.goods_name,b.factory_id,a.memo,b.order_id,a.order_status ";
                                $sql = "SELECT $fields FROM db_batchorder_list a LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id WHERE a.del_flag = 0 AND a.order_status = 0 AND a.id = '{$id}' ";
                                $result = $this->db->query($sql)->row_array();
                                if(!empty($result)){
                                    $arr_batchorder_list['caijian_id'] = $arr_caij[$k];
                                    $arr_batchorder_list['workers_id'] = $arr_work[$k];
                                    $arr_batchorder_list['order_status'] = 6;
                                    $this->db->where('id',$result['id']);
                                    $this->db->update('db_batchorder_list',$arr_batchorder_list);
                                    //db_stocks_list库存
                                    //$arr_stocks_list['goods_code'] = $result['goods_code'];
                                    //$arr_stocks_list['goods_name'] = $result['goods_name'];
                                    //$arr_stocks_list['stock_num'] = $arr_num[$k];
                                    //$arr_stocks_list['product_type'] = $result['product_type'];
                                    //$arr_stocks_list['userid'] = $_COOKIE['userid'];
                                    //$arr_stocks_list['create_user'] = $_COOKIE['username'];
                                    //$arr_stocks_list['createtime'] = $date;
                                    //$this->db->insert('db_stocks_list',$arr_stocks_list);
                                    //插入原有数据库表 库存表 d_savenum
                                    $arr_stocks_list['productsku'] = $result['goods_code'];
                                    $arr_stocks_list['productname'] = $result['goods_name'];
                                    $arr_stocks_list['productid'] = $result['goods_id'];
                                    $arr_stocks_list['producttypename'] = $result['product_type'];
                                    $arr_stocks_list['updateoper'] = $_COOKIE['userid'];
                                    $arr_stocks_list['updatetime'] = $date;
                                    $arr_stocks_list['factory'] = $result['factory_id'];
                                    //存在则更新，不存在则插入
                                    $sql_sel = "SELECT * FROM d_savenum WHERE productsku = '{$result['goods_code']}' AND productid = '{$result['goods_id']}' and producttypename = '{$result['product_type']}' ";
                                    $sql_rs = $this->db->query($sql_sel)->row_array();
                                    if($sql_rs){
                                        $sql_upd = "UPDATE d_savenum SET updatetime= '{$date}',updateoper = {$_COOKIE['userid']},savenum = savenum+$arr_num[$k] WHERE id = {$sql_rs['id']} ";
                                        $upd_rs = $this->db->query($sql_upd);
                                        //入库记录日志表，入库表记录等
                                        //插入入库记录日志表，入库记录等
                                        $arr_stocks_log['productsku'] = $result['goods_code'];
                                        $arr_stocks_log['productname'] = $result['goods_name'];
                                        $arr_stocks_log['productid'] = $result['goods_id'];
                                        $arr_stocks_log['oldsavenum'] = $sql_rs['savenum'];
                                        $arr_stocks_log['newsavenum'] = $sql_rs['savenum']+$arr_num[$k];
                                        $arr_stocks_log['producttypename'] = $result['product_type'];
                                        $arr_stocks_log['updateoper'] = $_COOKIE['userid'];
                                        $arr_stocks_log['updatetime'] = $date;
                                        $arr_stocks_log['savenumid'] = $sql_rs['id'];
                                        $arr_stocks_log['descr'] = "订单完成自动生成该库存!！";
                                        $this->db->insert('d_savenumlog',$arr_stocks_log);
                                        //插入入库记录表
                                        $arr_stocks_in['productid'] = $result['goods_id'];
                                        $arr_stocks_in['productsku'] = $result['goods_code'];
                                        $arr_stocks_in['oldsavenum'] = $sql_rs['savenum'];
                                        $arr_stocks_in['insavenum'] = $arr_num[$k];
                                        $arr_stocks_in['newsavenum'] = $sql_rs['savenum']+$arr_num[$k];
                                        $arr_stocks_in['descr'] = "订单完成自动生成该库存!！";
                                        $arr_stocks_in['createtime'] = $date;
                                        $arr_stocks_in['createoper'] = $_COOKIE['userid'];
                                        $arr_stocks_in['productname'] = $result['goods_name'];
                                        $arr_stocks_in['factory'] = $result['factory_id'];
                                        $arr_stocks_in['savenumid'] = $sql_rs['id'];
                                        $arr_stocks_in['producttypename'] = $result['product_type'];
                                        $arr_stocks_in['outfactory'] = $result['factory_id']; //外发工厂目前默认跟工厂一样
                                        $arr_stocks_in['orderid'] = $result['order_id']; //订单号
                                        $this->db->insert('d_addsavenum',$arr_stocks_in);

                                    }else{
                                        //插入相关数据
                                        $arr_stocks_list['savenum'] = `savenum`+$arr_num[$k];
                                        $this->db->insert('d_savenum',$arr_stocks_list);
                                        $savenumid = $this->db->insert_id(); //获取插入的id号
                                        //插入入库记录日志表，入库记录等
                                        $arr_stocks_log['productsku'] = $result['goods_code'];
                                        $arr_stocks_log['productname'] = $result['goods_name'];
                                        $arr_stocks_log['productid'] = $result['goods_id'];
                                        $arr_stocks_log['oldsavenum'] = 0;
                                        $arr_stocks_log['newsavenum'] = $arr_num[$k];
                                        $arr_stocks_log['producttypename'] = $v['product_type'];
                                        $arr_stocks_log['updateoper'] = $_COOKIE['userid'];
                                        $arr_stocks_log['updatetime'] = $date;
                                        $arr_stocks_log['savenumid'] = $savenumid;
                                        $arr_stocks_log['descr'] = "订单完成自动生成该库存!！";
                                        $this->db->insert('d_savenumlog',$arr_stocks_log);
                                        //插入入库记录表
                                        $arr_stocks_in['productid'] = $result['goods_id'];
                                        $arr_stocks_in['productsku'] = $result['goods_code'];
                                        $arr_stocks_in['oldsavenum'] = 0;
                                        $arr_stocks_in['insavenum'] = $arr_num[$k];
                                        $arr_stocks_in['newsavenum'] = $arr_num[$k];
                                        $arr_stocks_in['descr'] = "订单完成自动生成该库存!！";
                                        $arr_stocks_in['createtime'] = $date;
                                        $arr_stocks_in['createoper'] = $_COOKIE['userid'];
                                        $arr_stocks_in['productname'] = $result['goods_name'];
                                        $arr_stocks_in['factory'] = $result['factory_id'];
                                        $arr_stocks_in['savenumid'] = $savenumid;
                                        $arr_stocks_in['producttypename'] = $result['product_type'];
                                        $arr_stocks_in['outfactory'] = $result['factory_id']; //外发工厂目前默认跟工厂一样
                                        $arr_stocks_in['orderid'] = $result['order_id']; //订单号
                                        $this->db->insert('d_addsavenum',$arr_stocks_in);
                                    }

                                }else{
                                    continue;
                                }
                            }
                        }
                    //整体操作结束 end
                }elseif($data['status']==7){
                    $arr_things['details'] = "状态：工厂验货完成被修改为：公司验收";
                }elseif($data['status']==8){
                    $arr_things['details'] = "状态：公司验货完成被修改为：确认打款";
                }elseif($data['status']==2){
                    $arr_things['details'] = "状态：确认打款被修改为：已完成";
                }else{
                }
                $arr_things['username'] = $_COOKIE['username'];
                $arr_things['userid'] = $_COOKIE['userid'];
                $this->db->insert('db_batchorder_log', $arr_things);
            }
        //获取工厂列表
        $factorys = $this->fun->getdatabaseslist("db_factory");
        $this->tpl->assign("factorys", $factorys);
        //获取生产工厂
        $producefactorys = $this->config->item('producefactorys');
        $this->tpl->assign("producefactorys", explode("|", $producefactorys));
        //var_dump(explode("|",$producefactorys));exit;
        //显示相关数据
        $fields = "a.id,a.batchorder_id,a.product_type,a.product_num,a.caijian_id,a.workers_id,b.goods_code,b.goods_name,d.thumb_url,b.price,a.memo ";
        $sql = "SELECT $fields FROM db_batchorder_list a " .
            "LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id " .
            "LEFT JOIN db_goods c ON b.goods_code = c.goods_sku " .
            "LEFT JOIN db_goods_images d ON c.goods_id = d.goods_id " .
            " WHERE a.batchorder_id = '{$order_id}' GROUP BY a.id ";
        $result = $this->db->query($sql)->result_array();
        $this->tpl->assign("batchorder_list", $result);
        $res = $this->db->query("SELECT * FROM db_batchorder_log WHERE order_id = '$order_id' ORDER BY id DESC ")->result_array();
        $this->tpl->assign("logs", $res);
        // var_dump($result);exit;
        //$this->tpl->display('factory/batchorderupd.tpl');
        $path = "batchorder/updBatchOrder?order_id={$order_id}";
        $url = base_url($path);
        redirect($url);
		}
        if($op == "endFlag"){
            $order_id = trim($this->input->post('order_id'));
            $this->db->update("db_batchorder",array('end_flag'=>1),"order_id = ".$order_id);
            if($this->db->affected_rows()){
                $arr_back = array('code'=>1,'msg'=>"操作成功");
                echo json_encode($arr_back);exit;
            }else{
                $arr_back = array('code'=>0,'msg'=>"操作失败");
                echo json_encode($arr_back);exit;
            }


        }


        //单个工厂验货完成,同时对库存操作
        if($op =="factorycheck"){
            $id = $this->input->post('id');  //batchorder_list的id号
            $order_id = $this->input->post('order_id');
            $data['caijian_id'] = $this->input->post('caijian');
            $data['workers_id'] = $this->input->post('workers');
            $data['price'] = $this->input->post('price'); //价格
            $data['memo'] = $this->input->post('memo');  //备注同样可以修改
            //生产工厂
            $data['produce_factory'] = $this->input->post('produce_factory'); //id格式

            $data['order_status'] = 6;
            $stock_num = $this->input->post('stock_num'); //库存数
            $date = date("Y-m-d H:i:s");
            //$status = $this->input->post('status'); 该参数默认插入6 为工厂验货已经完成的标记
            //判断该生产是否为一批生产中的最后一个
            $s = "SELECT a.id,b.goods_code,b.goods_name,a.product_type,a.order_status,c.goods_id,b.factory_id,b.order_id,a.product_num,a.caijian_id,a.workers_id,a.price,a.memo,a.batchorder_id,a.produce_factory FROM db_batchorder_list a ".
                   " LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id ".
                  " LEFT JOIN db_goods c ON b.goods_code = c.goods_sku ".
                " WHERE a.batchorder_id = $order_id AND a.del_flag = 0 AND a.order_status = 0 GROUP BY a.id ";
            $rs  = $this->db->query($s)->result_array();
            $this->db->trans_begin();
            //下面需要对库存表进行操作 d_savenum
            try{
                if(count($rs)>1){
                    foreach($rs as $k=>$v){
                        if($v['id']==$id){
                            $message = "";
                            $message.= "商品编号：{$v['goods_code']},型号：{$v['product_type']},工厂验货完成 <br/>";
                            if($data['caijian_id']&&$data['caijian_id']!=$v['caijian_id']){
                                //裁剪
                                $sql_f = "SELECT * FROM d_user WHERE id = '{$data['caijian_id']}' ";
                                $rs_f  = $this->db->query($sql_f)->row_array();
                                $message.="裁剪人员被修改为：{$rs_f['name']} ";
                                $arr_batchorder_list['caijian_id'] = $data['caijian_id'];
                            }
                            if($data['workers_id']&&$data['workers_id']!=$v['workers_id']){
                                //车工人员
                                $sql_f = "SELECT * FROM d_user WHERE id = '{$data['workers_id']}' ";
                                $rs_f  = $this->db->query($sql_f)->row_array();
                                $message.="车工人员被修改为：{$rs_f['name']} ";
                                $arr_batchorder_list['workers_id'] = $data['workers_id'];
                            }
                            if($data['price']&&$data['price']!=$v['price']){
                                $message.="商品价格由{$v['price']}被修改为：{$data['price']} ";
                                $arr_batchorder_list['price'] = $data['price'];
                            }
                            if($data['memo']){
                                $message.="备注新增内容：{$data['memo']} ";
                                $arr_batchorder_list['memo'] = $v['memo'].$data['memo'];
                            }
                            if($data['produce_factory']&&$data['produce_factory']!=$v['produce_factory']){
                                //生产工厂
                                $sql_f = "SELECT * FROM d_factory_produce WHERE id = '{$data['produce_factory']}' ";
                                $rs_f  = $this->db->query($sql_f)->row_array();
                                    $message.="生产工厂被修改为：{$rs_f['name']} ";
                                $arr_batchorder_list['produce_factory'] = $data['produce_factory'];
                            }
                            if($stock_num&&$stock_num!=$v['product_num']){
                                if($v['product_num']){
                                    $message.="生产数量由{$v['product_num']}被修改为：{$stock_num} ";
                                }else{
                                    $message.="生产数量被修改为：{$stock_num} ";
                                }
                                $arr_batchorder_list['product_num'] = $stock_num;

                                //更改生产数量 9/19
                                /**
                                $order_sql = "SELECT a.goods_id,a.product_num,b.cang FROM db_batchorder_list a LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id WHERE a.id = $id ";
                                $order_rs  = $this->db->query($order_sql)->result_array();
                                foreach($order_rs as $key=>$value){
                                    if($value['cang']=="2号仓"){
                                        $sql_goods = "SELECT * FROM db_goods_stock WHERE goods_id = {$value['goods_id']} AND storage_id = 2 ";
                                        $rs_goods  = $this->db->query($sql_goods)->row_array();
                                    }else{
                                        $sql_goods = "SELECT * FROM db_goods_stock WHERE goods_id = {$value['goods_id']} AND storage_id = 1 ";
                                        $rs_goods  = $this->db->query($sql_goods)->row_array();
                                    }
                                    if($rs_goods){
                                        $upd = "UPDATE db_goods_stock SET waitnum = {$stock_num} WHERE id = {$rs_goods['id']} ";
                                        $this->db->query($upd);
                                    }

                                }**/


                            }
                            //若修改相关参数则更新日志表
                            if($message){
                                //所有验货完成，更新日志表
                                $arr_logs['createtime'] = date("Y-m-d H:i:s");
                                $arr_logs['order_id'] = $v["batchorder_id"];
                                $arr_logs['goods_code'] = $v['goods_code'];
                                $arr_logs['details'] = $message;
                                $arr_logs['username'] = $_COOKIE['username'];
                                $arr_logs['userid'] = $_COOKIE['userid'];
                                $this->db->insert('db_batchorder_log', $arr_logs);
                            }



                            $arr_batchorder_list['order_status'] = 6;
                            $this->db->where('id',$id);
                            $this->db->update('db_batchorder_list',$arr_batchorder_list);  //批量订单列表
                            //db_stocks_list库存
                            //$arr_stocks_list['goods_code'] = $v['goods_code'];
                            //$arr_stocks_list['goods_name'] = $v['goods_name'];
                           // $arr_stocks_list['stock_num'] = $stock_num;
                           // $arr_stocks_list['product_type'] = $v['product_type'];
                            //$arr_stocks_list['userid'] = $_COOKIE['userid'];
                            //$arr_stocks_list['create_user'] = $_COOKIE['username'];
                            //$arr_stocks_list['createtime'] = $date;
                            //$this->db->insert('db_stocks_list',$arr_stocks_list);
                            //插入原有数据库表 库存表 d_savenum
                            $arr_stocks_list['productsku'] = $v['goods_code'];
                            $arr_stocks_list['productname'] = $v['goods_name'];
                            $arr_stocks_list['productid'] = $v['goods_id'];
                            $arr_stocks_list['producttypename'] = $v['product_type'];
                            $arr_stocks_list['updateoper'] = $_COOKIE['userid'];
                            $arr_stocks_list['updatetime'] = $date;
                            $arr_stocks_list['factory'] = $v['factory_id'];
                            //存在则更新，不存在则插入 获取最新一条记录
                            $sql_sel = "SELECT * FROM d_savenum WHERE productsku = '{$v['goods_code']}' AND producttypename = '{$v['product_type']}' ORDER BY id DESC ";
                            //$sql_sel = "SELECT * FROM d_savenum WHERE productsku = '{$v['goods_code']}' AND productid = '{$v['goods_id']}' and producttypename = '{$v['product_type']}' ";
                            $sql_rs = $this->db->query($sql_sel)->row_array();
                            if($sql_rs){
                                //更新库存表
                                $sql_upd = "UPDATE d_savenum SET updatetime= '{$date}',updateoper = {$_COOKIE['userid']},savenum = savenum+$stock_num WHERE id = {$sql_rs['id']} ";
                                $upd_rs = $this->db->query($sql_upd);
                                //入库记录日志表，入库表记录等
                                //插入入库记录日志表，入库记录等
                                $arr_stocks_log['productsku'] = $v['goods_code'];
                                $arr_stocks_log['productname'] = $v['goods_name'];
                                $arr_stocks_log['productid'] = $v['goods_id'];
                                $arr_stocks_log['oldsavenum'] = $sql_rs['savenum'];
                                $arr_stocks_log['newsavenum'] = $sql_rs['savenum']+$stock_num;
                                $arr_stocks_log['producttypename'] = $v['product_type'];
                                $arr_stocks_log['updateoper'] = $_COOKIE['userid'];
                                $arr_stocks_log['updatetime'] = $date;
                                $arr_stocks_log['savenumid'] = $sql_rs['id'];
                                $arr_stocks_log['descr'] = "订单完成自动生成该库存!！";
                                $this->db->insert('d_savenumlog',$arr_stocks_log);
                                //插入入库记录表
                                $arr_stocks_in['productid'] = $v['goods_id'];
                                $arr_stocks_in['productsku'] = $v['goods_code'];
                                $arr_stocks_in['oldsavenum'] = $sql_rs['savenum'];
                                $arr_stocks_in['insavenum'] = $stock_num;
                                $arr_stocks_in['newsavenum'] = $sql_rs['savenum']+$stock_num;
                                $arr_stocks_in['descr'] = "订单完成自动生成该库存!！";
                                $arr_stocks_in['createtime'] = $date;
                                $arr_stocks_in['createoper'] = $_COOKIE['userid'];
                                $arr_stocks_in['productname'] = $v['goods_name'];
                                $arr_stocks_in['factory'] = $v['factory_id'];
                                $arr_stocks_in['savenumid'] = $sql_rs['id'];
                                $arr_stocks_in['producttypename'] = $v['product_type'];
                                $arr_stocks_in['outfactory'] = $v['factory_id']; //外发工厂目前默认跟工厂一样
                                $arr_stocks_in['orderid'] = $v['order_id']; //订单号
                                $this->db->insert('d_addsavenum',$arr_stocks_in);

                            }else{
                                //插入相关数据 库存表
                                $arr_stocks_list['savenum'] = $stock_num;
                                $this->db->insert('d_savenum',$arr_stocks_list);
                                $savenumid = $this->db->insert_id(); //获取插入的id号
                                //插入入库记录日志表，入库记录等
                                $arr_stocks_log['productsku'] = $v['goods_code'];
                                $arr_stocks_log['productname'] = $v['goods_name'];
                                $arr_stocks_log['productid'] = $v['goods_id'];
                                $arr_stocks_log['oldsavenum'] = 0;
                                $arr_stocks_log['newsavenum'] = $stock_num;
                                $arr_stocks_log['producttypename'] = $v['product_type'];
                                $arr_stocks_log['updateoper'] = $_COOKIE['userid'];
                                $arr_stocks_log['updatetime'] = $date;
                                $arr_stocks_log['savenumid'] = $savenumid;
                                $arr_stocks_log['descr'] = "订单完成自动生成该库存!！";
                                $this->db->insert('d_savenumlog',$arr_stocks_log);
                                //插入入库记录表
                                $arr_stocks_in['productid'] = $v['goods_id'];
                                $arr_stocks_in['productsku'] = $v['goods_code'];
                                $arr_stocks_in['oldsavenum'] = 0;
                                $arr_stocks_in['insavenum'] = $stock_num;
                                $arr_stocks_in['newsavenum'] = $stock_num;
                                $arr_stocks_in['descr'] = "订单完成自动生成该库存!！";
                                $arr_stocks_in['createtime'] = $date;
                                $arr_stocks_in['createoper'] = $_COOKIE['userid'];
                                $arr_stocks_in['productname'] = $v['goods_name'];
                                $arr_stocks_in['factory'] = $v['factory_id'];
                                $arr_stocks_in['savenumid'] = $savenumid;
                                $arr_stocks_in['producttypename'] = $v['product_type'];
                                $arr_stocks_in['outfactory'] = $v['factory_id']; //外发工厂目前默认跟工厂一样
                                $arr_stocks_in['orderid'] = $v['order_id']; //订单号
                                $this->db->insert('d_addsavenum',$arr_stocks_in);
                            }

                        }
                    }

                }else{
                    //batchorder_list
                    $message = "";
                    $message.= "商品编号：{$rs[0]['goods_code']},型号：{$rs[0]['product_type']},工厂验货完成 <br/>";
                    /**
                    if($data['caijian_id']){
                        $arr_batchorder_list['caijian_id'] = $data['caijian_id'];
                    }
                    if($data['workers_id']){
                        $arr_batchorder_list['workers_id'] = $data['workers_id'];
                    }
                    if($data['price']){
                        $arr_batchorder_list['price'] = $data['price'];
                    }
                    if($data['memo']){
                        $arr_batchorder_list['memo'] = $data['memo'];
                    }
                    if($stock_num){
                        $arr_batchorder_list['product_num'] = $stock_num;
                    }**/
                    if($data['caijian_id']&&$data['caijian_id']!=$rs[0]['caijian_id']){
                        //裁剪
                        $sql_f = "SELECT * FROM d_user WHERE id = '{$data['caijian_id']}' ";
                        $rs_f  = $this->db->query($sql_f)->row_array();
                        $message.="裁剪人员被修改为：{$rs_f['name']} ";
                        $arr_batchorder_list['caijian_id'] = $data['caijian_id'];
                    }
                    if($data['workers_id']&&$data['workers_id']!=$rs[0]['workers_id']){
                        //车工人员
                        $sql_f = "SELECT * FROM d_user WHERE id = '{$data['workers_id']}' ";
                        $rs_f  = $this->db->query($sql_f)->row_array();
                        $message.="车工人员被修改为：{$rs_f['name']} ";
                        $arr_batchorder_list['workers_id'] = $data['workers_id'];
                    }
                    if($data['price']&&$data['price']!=$rs[0]['price']){
                        $message.="商品价格由{$rs[0]['price']}被修改为：{$data['price']} ";
                        $arr_batchorder_list['price'] = $data['price'];
                    }
                    if($data['produce_factory']&&$data['produce_factory']!=$rs[0]['produce_factory']){
                        //生产工厂
                        $sql_f = "SELECT * FROM d_factory_produce WHERE id = '{$data['produce_factory']}' ";
                        $rs_f  = $this->db->query($sql_f)->row_array();
                        $message.="生产工厂被修改为：{$rs_f['name']} ";
                        $arr_batchorder_list['produce_factory'] = $data['produce_factory'];
                    }
                    if($data['memo']){
                        $message.="备注新增内容：{$data['memo']} ";
                        $arr_batchorder_list['memo'] = $rs[0]['memo'].$data['memo'];
                    }
                    if($stock_num&&$stock_num!=$rs[0]['product_num']){
                        if($rs[0]['product_num']){
                            $message.="生产数量由{$rs[0]['product_num']}被修改为：{$stock_num} ";
                        }else{
                            $message.="生产数量被修改为：{$stock_num} ";
                        }
                        $arr_batchorder_list['product_num'] = $stock_num;

                        //更改生产数量 9/19
                        /**
                        $order_sql = "SELECT a.goods_id,a.product_num,b.cang FROM db_batchorder_list a LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id WHERE a.id = $id ";
                        $order_rs  = $this->db->query($order_sql)->result_array();
                        foreach($order_rs as $key=>$value){
                            if($value['cang']=="2号仓"){
                                $sql_goods = "SELECT * FROM db_goods_stock WHERE goods_id = {$value['goods_id']} AND storage_id = 2 ";
                                $rs_goods  = $this->db->query($sql_goods)->row_array();
                            }else{
                                $sql_goods = "SELECT * FROM db_goods_stock WHERE goods_id = {$value['goods_id']} AND storage_id = 1 ";
                                $rs_goods  = $this->db->query($sql_goods)->row_array();
                            }
                            if($rs_goods){
                                $upd = "UPDATE db_goods_stock SET waitnum = {$stock_num} WHERE id = {$rs_goods['id']} ";
                                $this->db->query($upd);
                            }

                        }**/
                    }
                    /**
                    $arr_batchorder_list['caijian_id'] = $data['caijian_id'];
                    $arr_batchorder_list['workers_id'] = $data['workers_id'];
                    $arr_batchorder_list['price'] = $data['price'];
                    $arr_batchorder_list['memo'] = $data['memo'];
                     * */
                    $arr_batchorder_list['order_status'] = 6;
                    $arr_batchorder_list['createtime'] = $date;
                    $this->db->where('id',$id);
                    $this->db->update('db_batchorder_list',$arr_batchorder_list); //批量订单列表
                    //db_stocks_list库存
                    //插入原有数据库表 库存表 d_savenum
                    $arr_stocks_list['productsku'] = $rs[0]['goods_code'];
                    $arr_stocks_list['productname'] = $rs[0]['goods_name'];
                    $arr_stocks_list['productid'] = $rs[0]['goods_id'];
                    $arr_stocks_list['producttypename'] = $rs[0]['product_type'];
                    $arr_stocks_list['updateoper'] = $_COOKIE['userid'];
                    $arr_stocks_list['updatetime'] = $date;
                    $arr_stocks_list['factory'] = $rs[0]['factory_id'];
                    //存在则更新，不存在则插入
                    $sql_sel = "SELECT * FROM d_savenum WHERE productsku = '{$rs[0]['goods_code']}' AND producttypename = '{$rs[0]['product_type']}' ORDER BY id DESC ";
                    //$sql_sel = "SELECT * FROM d_savenum WHERE productsku = '{$rs[0]['goods_code']}' AND productid = '{$rs[0]['goods_id']}' and producttypename = '{$rs[0]['product_type']}' ";
                    $sql_rs = $this->db->query($sql_sel)->row_array();
                    //此处需要加个判断，判断该id是否状态不是6
                    $ss = "SELECT a.id,a.order_status FROM db_batchorder_list a ".
                        " WHERE a.id = $id ";
                    $rss  = $this->db->query($ss)->row_array();
                    if($sql_rs){
                       // if($rss['order_status']==6){
                            //修改库存数
                         //   $sql_upd = "UPDATE d_savenum SET updatetime= '{$date}',updateoper = {$_COOKIE['userid']},savenum = $stock_num WHERE id = {$sql_rs['id']} ";
                        //    $upd_rs = $this->db->query($sql_upd);
                      //  }else{
                            //更新库存数
                            $sql_upd = "UPDATE d_savenum SET updatetime= '{$date}',updateoper = {$_COOKIE['userid']},savenum = savenum+$stock_num WHERE id = {$sql_rs['id']} ";
                            $upd_rs = $this->db->query($sql_upd);
                     //   }
                        //入库记录日志表，入库表记录等
                       // $sql_sel = "SELECT * FROM d_savenum WHERE productsku = '{$rs[0]['goods_code']}' AND productid = '{$rs[0]['goods_id']}' and producttypename = '{$rs[0]['product_type']}' ";
                        //$sql_rs = $this->db->query($sql_sel)->row_array();
                        //插入入库记录日志表，入库记录等
                        $arr_stocks_log['productsku'] = $rs[0]['goods_code'];
                        $arr_stocks_log['productname'] = $rs[0]['goods_name'];
                        $arr_stocks_log['productid'] = $rs[0]['goods_id'];
                        $arr_stocks_log['oldsavenum'] = $sql_rs['savenum'];
                        $arr_stocks_log['newsavenum'] = $sql_rs['savenum']+$stock_num;
                        $arr_stocks_log['producttypename'] = $rs[0]['product_type'];
                        $arr_stocks_log['updateoper'] = $_COOKIE['userid'];
                        $arr_stocks_log['updatetime'] = $date;
                        $arr_stocks_log['savenumid'] = $sql_rs['id'];
                        $arr_stocks_log['descr'] = "订单完成自动生成该库存!！";
                        $this->db->insert('d_savenumlog',$arr_stocks_log);
                        //插入入库记录表
                        $arr_stocks_in['productid'] = $rs[0]['goods_id'];
                        $arr_stocks_in['productsku'] = $rs[0]['goods_code'];
                        $arr_stocks_in['oldsavenum'] = $sql_rs['savenum'];
                        $arr_stocks_in['insavenum'] = $stock_num;
                        $arr_stocks_in['newsavenum'] = $sql_rs['savenum']+$stock_num;
                        $arr_stocks_in['descr'] = "订单完成自动生成该库存!！";
                        $arr_stocks_in['createtime'] = $date;
                        $arr_stocks_in['createoper'] = $_COOKIE['userid'];
                        $arr_stocks_in['productname'] = $rs[0]['goods_name'];
                        $arr_stocks_in['factory'] = $rs[0]['factory_id'];
                        $arr_stocks_in['savenumid'] = $sql_rs['id'];
                        $arr_stocks_in['producttypename'] = $rs[0]['product_type'];
                        $arr_stocks_in['outfactory'] = $rs[0]['factory_id']; //外发工厂目前默认跟工厂一样
                        $arr_stocks_in['orderid'] = $rs[0]['order_id']; //订单号
                        $this->db->insert('d_addsavenum',$arr_stocks_in);

                    }else{
                        //插入相关数据
                        $arr_stocks_list['savenum'] = $stock_num;
                        $this->db->insert('d_savenum',$arr_stocks_list);
                        $savenumid = $this->db->insert_id(); //获取插入的id号
                        //$arr_back = array('code'=>0,'msg'=>$this->db->last_query());
                        //echo json_encode($arr_back);exit;
                        //插入入库记录日志表，入库记录等
                        $arr_stocks_log['productsku'] = $rs[0]['goods_code'];
                        $arr_stocks_log['productname'] = $rs[0]['goods_name'];
                        $arr_stocks_log['productid'] = $rs[0]['goods_id'];
                        $arr_stocks_log['oldsavenum'] = 0;
                        $arr_stocks_log['newsavenum'] = $stock_num;
                        $arr_stocks_log['producttypename'] = $rs[0]['product_type'];
                        $arr_stocks_log['updateoper'] = $_COOKIE['userid'];
                        $arr_stocks_log['updatetime'] = $date;
                        $arr_stocks_log['savenumid'] = $savenumid;
                        $arr_stocks_log['descr'] = "订单完成自动生成该库存!！";
                        $this->db->insert('d_savenumlog',$arr_stocks_log);
                        //插入入库记录表
                        $arr_stocks_in['productid'] = $rs[0]['goods_id'];
                        $arr_stocks_in['productsku'] = $rs[0]['goods_code'];
                        $arr_stocks_in['oldsavenum'] = 0;
                        $arr_stocks_in['insavenum'] = $stock_num;
                        $arr_stocks_in['newsavenum'] = $stock_num;
                        $arr_stocks_in['descr'] = "订单完成自动生成该库存!！";
                        $arr_stocks_in['createtime'] = $date;
                        $arr_stocks_in['createoper'] = $_COOKIE['userid'];
                        $arr_stocks_in['productname'] = $rs[0]['goods_name'];
                        $arr_stocks_in['factory'] = $rs[0]['factory_id'];
                        $arr_stocks_in['savenumid'] = $savenumid;
                        $arr_stocks_in['producttypename'] = $rs[0]['product_type'];
                        $arr_stocks_in['outfactory'] = $rs[0]['factory_id']; //外发工厂目前默认跟工厂一样
                        $arr_stocks_in['orderid'] = $rs[0]['order_id']; //订单号
                        $this->db->insert('d_addsavenum',$arr_stocks_in);
                    }
                    //batchorder
                   // if($rss['order_status']==6){ //若状态位6，说明只是修改相关库存数据
                   // }else{
                        $arr_batchorder['status'] = 6;
                        $this->db->where('order_id',$order_id);
                        $this->db->update('db_batchorder',$arr_batchorder);
                   // }

                    //若修改相关参数则更新日志表
                    if($message){
                        //所有验货完成，更新日志表
                        $arr_logs['createtime'] = date("Y-m-d H:i:s");
                        $arr_logs['order_id'] = $order_id;
                        $arr_logs['goods_code'] = $rs[0]['goods_code'];
                        $arr_logs['details'] = $message;
                        $arr_logs['username'] = $_COOKIE['username'];
                        $arr_logs['userid'] = $_COOKIE['userid'];
                        $this->db->insert('db_batchorder_log', $arr_logs);
                    }




                    //所有验货完成，更新日志表
                    $arr_things['createtime'] = date("Y-m-d H:i:s");
                    $arr_things['order_id'] = $order_id;
                    $arr_things['goods_code'] = $rs[0]['goods_code'];
                    $arr_things['details'] = "状态：确认交货被修改为：工厂验货完成";
                    $arr_things['username'] = $_COOKIE['username'];
                    $arr_things['userid'] = $_COOKIE['userid'];
                    $this->db->insert('db_batchorder_log', $arr_things);

                }
                $this->db->trans_commit();
                $arr_back = array('code'=>1,'msg'=>"成功");
                echo json_encode($arr_back);exit;
            }catch (Exception $e){
                $arr_back = array('code'=>0,'msg'=>$e->getMessage());
                $this->db->trans_rollback();
                echo json_encode($arr_back);exit;
            }

        } //factoryCheck结束







	}
	
	



}